package zk;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;

public class ListServlet extends HttpServlet {
    private Client client;

    public void init(ServletConfig config){
        try {
            client = new Client();
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        System.out.println("Initialization finished");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ArrayList<String>  ids = new ArrayList<String>();
        ArrayList<String> names = new ArrayList<String>();
        try {
            Connection conn = client.getConnection();
//            PreparedStatement ps = conn.prepareStatement("select * from zk_homework");
//            ps.execute().var
            Statement s = conn.createStatement();
            String sql = "select * from zk_homework";
            ResultSet rs = s.executeQuery(sql);
            while(rs.next()){
                String id = rs.getString(1);
                String name = rs.getString(2);
                ids.add(id);
                names.add(name);
            }
            rs.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        resp.getWriter().println("<table>");
        for(int i = 0; i< ids.size(); i++){
            resp.getWriter().println("<tr>");
            resp.getWriter().println("<td>" + ids.get(i) + "</td>");
            resp.getWriter().println("<td>" + names.get(i) + "</td>");
            resp.getWriter().println("</tr>");
        }
        resp.getWriter().println("</table>");
    }
}
